#!/bin/sh

export BASE_DIR=`cd $(dirname $0)/.; pwd`
nginx="${BASE_DIR}/nginx"
NGINX_CONF_FILE="${BASE_DIR}/conf/nginx-boot-linux-prod.conf"
prog="nginx"

lockfile="${BASE_DIR}/data/lock/subsys/nginx"
if [ ! -d "$lockfile" ]; then
        mkdir -p $lockfile
fi


start() {
    #[ -x $nginx ] || exit 5
    #[ -f $NGINX_CONF_FILE ] || exit 6
    #先检测nginx是否已经启动
    netstat -nlpt | grep nginx &> /dev/null
    if [ $? -eq 0 ];then
      echo "nginx已经启动！"
    else
      echo -n $"Starting $prog: "
      $nginx -p ${BASE_DIR} -c $NGINX_CONF_FILE
      retval=$?
      echo
      [ $retval -eq 0 ] && touch $lockfile
    fi
    #return $retval
}

stop() {
    #先检测nginx是否已经启动
    netstat -nlpt | grep nginx &> /dev/null
    if [ $? -eq 0 ];then
      echo -n $"Stopping $prog: "
      $nginx  -p ${BASE_DIR} -c $NGINX_CONF_FILE -s stop
      retval=$?
      echo
      [ $retval -eq 0 ] && rm -rf $lockfile
    else
       echo "nginx未启动！"
    fi
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    $nginx  -p ${BASE_DIR} -c $NGINX_CONF_FILE -s reload
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -p ${BASE_DIR} -t -c $NGINX_CONF_FILE
}

rh_status() {
  netstat -nlpt | grep nginx &> /dev/null
  if [ $? -eq 0 ];then
                echo "nginx已经启动！"
        else
                echo "nginx没有运行！"
        fi
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        $1
        ;;
    stop)
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac